package com.simafei.flow.core.common;

import cn.hutool.core.util.StrUtil;
import org.mvel2.PropertyAccessException;

import java.util.HashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Set;

/**
 * @author fengpengju
 */
public class Predicate {

    public static boolean eval(Criteria criteria, Map<String, Object> params) {
        if (Objects.isNull(criteria)) {
            return true;
        }
        String when = criteria.toExpr(params);
        if (StrUtil.isEmpty(when)) {
            return true;
        }
        Set<String> usingFields = new HashSet<>(criteria.fields());
        try {
            return (boolean) ExpressionExecutor.execute(when, params, usingFields);
        } catch (PropertyAccessException ignored) {
            // 如果表达式中需要的变量不存在，该条件直接返回false
            return false;
        }
    }
}
